package com.starblink.login.editpersonalinfo.editusername.ui

import android.content.Intent
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.login.databinding.ActivityEditUserNameBinding

/**
 * 编辑用户名
 */
@Route(path = RoutePage.Login.EDIT_USERNAME)
class EditUserNameActivity : BaseTVMActivity<ActivityEditUserNameBinding, EditUserNameVM>() {
    @Autowired(name = LoginManager.KEY_USERNAME)
    @JvmField
    var username: String = ""

    override fun initViewBinding(): ActivityEditUserNameBinding =
        ActivityEditUserNameBinding.inflate(layoutInflater)

    override fun initView() {
        super.initView()
        viewBinding.titleBar.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }
        })

        viewBinding.etUsername.setOnEditInputListener {
            viewBinding.tvErrorHint.visibleOrGone(false)
            setInputLength(it.length)
            viewBinding.btnBottom.isEnabled = it.isNotEmpty()
        }
        viewBinding.etUsername.text = username // 设置初始值

        viewBinding.btnBottom.click {
            val res = LoginManager.validateUserName(viewBinding.etUsername.text)
            if (res == null) {
                // 用户名OK
                setResult(RESULT_OK, Intent().putExtra(LoginManager.KEY_USERNAME, viewBinding.etUsername.text))
                finish()
            } else {
                viewBinding.tvErrorHint.visibleOrGone(true)
                viewBinding.tvErrorHint.text = res
            }
        }
    }

    private fun setInputLength(inputLength: Int){
        viewBinding.tvInputLength.text = "$inputLength/25"
    }

}